<template>
  <div class="advanced-stats">
    <!-- 统计卡片头部 -->
    <div class="stats-header">
      <h3 class="stats-title">{{ title }}</h3>
      <div class="stats-actions">
        <el-select v-model="timeRange" size="small" @change="handleTimeRangeChange" class="range-select">
          <el-option label="近7天" value="7d"></el-option>
          <el-option label="近30天" value="30d"></el-option>
          <el-option label="近90天" value="90d"></el-option>
          <el-option label="全部" value="all"></el-option>
        </el-select>
        <el-button size="small" type="text" @click="refreshData">
          <el-icon><el-icon-Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 统计数据网格 -->
    <div class="stats-grid">
      <div v-for="(stat, index) in statsData" :key="index" class="stat-item">
        <div class="stat-icon" :class="stat.iconClass">
          <el-icon :size="24"><component :is="stat.icon" /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value" :class="{ 'highlight': stat.highlight }">
            {{ stat.value }}
          </div>
          <div class="stat-label">{{ stat.label }}</div>
          <div class="stat-change" :class="stat.changeType">
            <el-icon v-if="stat.change > 0"><el-icon-CaretTop /></el-icon>
            <el-icon v-else-if="stat.change < 0"><el-icon-CaretBottom /></el-icon>
            <el-icon v-else><el-icon-minus /></el-icon>
            {{ Math.abs(stat.change) }}%
            <span class="change-period">{{ stat.changePeriod }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 趋势图表 -->
    <div class="trend-chart" v-if="showChart">
      <div ref="chartRef" class="chart-container"></div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'AdvancedStats',
  props: {
    title: {
      type: String,
      default: '高级统计分析'
    },
    showChart: {
      type: Boolean,
      default: true
    },
    chartType: {
      type: String,
      default: 'line'
    },
    initialStats: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const timeRange = ref('30d')
    const chartRef = ref(null)
    const chartInstance = ref(null)
    const statsData = ref(props.initialStats.length > 0 ? props.initialStats : getDefaultStats())
    const isLoading = ref(false)

    // 默认统计数据
    function getDefaultStats() {
      return [
        {
          value: '87%',
          label: '修复率',
          change: 5,
          changeType: 'positive',
          changePeriod: '较上月',
          icon: 'el-icon-SuccessFilled',
          iconClass: 'success',
          highlight: true
        },
        {
          value: '12',
          label: '新增漏洞',
          change: -3,
          changeType: 'negative',
          changePeriod: '较上周',
          icon: 'el-icon-WarningFilled',
          iconClass: 'warning'
        },
        {
          value: '48h',
          label: '平均修复时间',
          change: -12,
          changeType: 'negative',
          changePeriod: '较上月',
          icon: 'el-icon-Clock',
          iconClass: 'info'
        },
        {
          value: '96%',
          label: '扫描覆盖率',
          change: 2,
          changeType: 'positive',
          changePeriod: '较上周',
          icon: 'el-icon-CircleCheck',
          iconClass: 'success'
        }
      ]
    }

    // 处理时间范围变化
    const handleTimeRangeChange = () => {
      loadStatsData()
    }

    // 加载统计数据
    const loadStatsData = async () => {
      isLoading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        // 这里可以根据timeRange加载不同的数据
        // 示例中仅更新随机变化
        statsData.value = statsData.value.map(stat => ({
          ...stat,
          change: Math.floor(Math.random() * 20) - 10 // 随机变化-10到10%
        }))
        updateChart()
      } catch (error) {
        ElMessage.error('加载统计数据失败')
      } finally {
        isLoading.value = false
      }
    }

    // 刷新数据
    const refreshData = () => {
      loadStatsData()
    }

    // 初始化图表
    const initChart = () => {
      if (!props.showChart || !chartRef.value) return
      
      // 这里可以集成ECharts或其他图表库
      // 示例中仅作为占位符
      const container = chartRef.value
      container.innerHTML = '<div class="chart-placeholder">图表将在这里渲染</div>'
    }

    // 更新图表
    const updateChart = () => {
      if (!chartInstance.value) {
        initChart()
      } else {
        // 更新图表数据
        // chartInstance.value.setOption(...)  
      }
    }

    // 监听属性变化
    watch(() => props.showChart, (newVal) => {
      if (newVal) {
        setTimeout(() => {
          initChart()
        }, 100)
      }
    })

    onMounted(() => {
      loadStatsData()
      if (props.showChart) {
        initChart()
      }
    })

    onUnmounted(() => {
      // 清理图表实例
      if (chartInstance.value) {
        // chartInstance.value.dispose()
      }
    })

    return {
      timeRange,
      statsData,
      chartRef,
      handleTimeRangeChange,
      refreshData
    }
  }
}
</script>

<style scoped>
.advanced-stats {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

/* 暗色模式支持 */
:global(.dark-mode) .advanced-stats {
  background: #1f2937;
  color: #f3f4f6;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f9ff;
}

:global(.dark-mode) .stats-header {
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

.stats-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

:global(.dark-mode) .stats-title {
  color: #f3f4f6;
}

.stats-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

:global(.dark-mode) .stat-item {
  background: #374151;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-icon.success {
  background: linear-gradient(135deg, #dcfce7, #bbf7d0);
  color: #22c55e;
}

.stat-icon.warning {
  background: linear-gradient(135deg, #fef9c3, #fde68a);
  color: #f59e0b;
}

.stat-icon.danger {
  background: linear-gradient(135deg, #fee2e2, #fca5a5);
  color: #ef4444;
}

.stat-icon.info {
  background: linear-gradient(135deg, #dbeafe, #bfdbfe);
  color: #3b82f6;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-value.highlight {
  background: linear-gradient(135deg, #60a5fa, #3b82f6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

:global(.dark-mode) .stat-value {
  color: #f3f4f6;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 2px;
}

:global(.dark-mode) .stat-label {
  color: #9ca3af;
}

.stat-change {
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-change.positive {
  color: #22c55e;
}

.stat-change.negative {
  color: #ef4444;
}

.stat-change.neutral {
  color: #6b7280;
}

.change-period {
  font-size: 11px;
  opacity: 0.8;
}

.trend-chart {
  margin-top: 20px;
  height: 280px;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.chart-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #9ca3af;
  font-size: 14px;
}
</style>